package com.umfb.config.zk;

import com.google.common.base.Splitter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.env.ConfigurablePropertyResolver;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by zcah on 18-4-19.
 */
public class ZooKeeperPropertySource {
    private static final String SERVER = "zk.server";
    private static final String NS = "zk.ns";
    private static final String PROJ = "zk.proj";
    private ConfigurablePropertyResolver resolver;

    protected final Log logger = LogFactory.getLog(getClass());

    public Properties props;

    String getProperty(String name) {
        if (props == null) {
            props = new Properties();
            try {
                this.fillCustomProperties(props);
            } catch (Exception e) {
                logger.error("fill customProperties error!" + e.toString());
            }
        }
        return props.get(name) == null ? null : props.get(name).toString();
    }

    void setConfigurablePropertyResolver(ConfigurablePropertyResolver resolver) {
        this.resolver = resolver;
    }

    private void fillCustomProperties(Properties props) throws Exception {
        UmfbConfig config = new ZooKeeperConfig(resolver.getProperty(SERVER), resolver.getProperty(NS),
                resolver.getProperty(PROJ));
//		UmfbConfig config = new ZooKeeperConfig(resolver.getProperty(SERVER), "dev",
//				resolver.getProperty(PROJ));
        byte[] data = config.getAllConfigForOnce();
        fillProperties(props, data);
    }

    private void fillProperties(Properties props, byte[] data) throws UnsupportedEncodingException {
        String configStr = new String(data, "UTF-8");

        String separator = System.getProperty("line.separator");

        for (String s : Splitter.on(separator).trimResults().omitEmptyStrings().split(configStr)) {
            int index = s.indexOf('=');
            if (index == -1)
                continue;

            String key = s.substring(0, index);
            String value = "";
            try {
                value = s.substring(index + 1);
            } catch (StringIndexOutOfBoundsException ex) {
                logger.error("zookeeper props parse error. key:[" + key + "], value:[" + s + "]");
            } finally {
                props.put(key, value);
                // 此处只往页面上注了http打头的props
                if (key.startsWith("http.") || key.startsWith("conf.") || key.startsWith("tp.")) {
                    ConstantConfig.UmfbConfig.put(key.startsWith("http.") ? key.substring(5) : key, value);
                }

            }
        }
        ConstantConfig.triggerConfigSetComplete();
    }

}
